package com.iecg.controller.app;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.iecg.api.dto.IecgBindDto;
import com.iecg.api.entity.IecgUser;
import com.iecg.filter.RequestHolder;
import com.iecg.service.IecgUserService;
import com.pig4cloud.pigx.common.core.constant.CacheConstants;
import com.pig4cloud.pigx.common.core.util.R;
import com.pig4cloud.pigx.common.log.annotation.SysLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@AllArgsConstructor
@RequestMapping("app/bind" )
@Api(value = "app_bind", tags = "App用户绑定")
public class AppWeixinBindController {

	private final IecgUserService userService;

	private final RedisTemplate  redisTemplate;

	/**
	 * 绑定Openid ,生成亲友码
	 * @param
	 * @return R
	 */
	@ApiOperation(value = "生成绑定码", notes = "生成绑定码")
	@SysLog("生成绑定码" )
	@GetMapping(value = {"/gen"})
	public R generateBindCode() {
		IecgUser iecgUser = userService.getSecurityUser();
		String  redidBindCode = (String) redisTemplate.opsForValue().get(CacheConstants.BIND_CODE + "_" + iecgUser.getId());
		if(redidBindCode != null){
			return R.ok(redidBindCode);
		}
		String bindCode = String.valueOf((int)((Math.random()*9+1)*100000));
		IecgUser exsitUser = userService.getOne(Wrappers.<IecgUser>query().lambda().eq(IecgUser::getBindCode, bindCode));
		if(exsitUser != null){
			return R.failed("生成绑定码失败");
		}
		iecgUser.setBindCode(bindCode);
		userService.updateById(iecgUser);
		redisTemplate.opsForValue().set(CacheConstants.BIND_CODE + "_" + iecgUser.getId(), bindCode);
		return R.ok(bindCode);
	}

	/**
	 * 绑定亲友
	 * @param iecgBindDto
	 * @return
	 */
	@ApiOperation(value = "绑定亲友", notes = "绑定亲友")
	@SysLog("绑定亲友" )
	@PostMapping
	public R bindFriend(@RequestBody IecgBindDto iecgBindDto){
		IecgUser bindToUser = userService.getOne(Wrappers.<IecgUser>query().lambda().eq(IecgUser::getBindCode, iecgBindDto.getBindCode()).eq(IecgUser::getRealName, iecgBindDto.getRealName()));
		if(bindToUser == null){
			return R.failed("姓名或绑定码错误");
		}
		String myOpenId = iecgBindDto.getOpenId();
		String mobile = RequestHolder.getParam();
		IecgUser my = userService.getOne(Wrappers.<IecgUser>query().lambda().eq(IecgUser::getName, mobile));
		my.setOpenId(myOpenId);
		userService.updateById(my);
		Long bindToUserId = bindToUser.getId();
		redisTemplate.opsForSet().add(CacheConstants.BIND_OTHERS + "_" + my.getId(), bindToUserId);
		redisTemplate.opsForSet().add(CacheConstants.BIND_ME + "_" + bindToUserId, my.getId());
		return R.ok();
	}


	/**
	 * 获取绑定列表
	 * @return
	 */
	@ApiOperation(value = "绑定列表", notes = "绑定列表")
	@SysLog("绑定列表" )
	@GetMapping("/bindlist/{openid}")
	public R getBindFriendList(@PathVariable("openid") String openId){
		IecgUser iecgUser = userService.getOne(Wrappers.<IecgUser>query().lambda().eq(IecgUser::getOpenId, openId));
		Set bindMeSet = redisTemplate.opsForSet().members(CacheConstants.BIND_ME + "_" + iecgUser.getId());
		Set bindOthersSet = redisTemplate.opsForSet().members(CacheConstants.BIND_OTHERS + "_" + iecgUser.getId());
		Map retMap = new HashMap<>();
		retMap.put("bindMeList", bindMeSet.stream().map(userId ->
			 userService.getById(Long.valueOf(userId.toString()))
		).collect(Collectors.toList()));
		retMap.put("bindOtherList", bindOthersSet.stream().map(userId ->
				userService.getById(Long.valueOf(userId.toString()))
		).collect(Collectors.toList()));
		return R.ok(retMap);
	}


	/**
	 * 微信接触绑定
	 * @param bindToUserId
	 * @return
	 */
	@ApiOperation(value = "解除绑定", notes = "解除绑定")
	@SysLog("解除绑定")
	@DeleteMapping("/{userid}")
	public R delBindItem(@PathVariable("userid") String bindToUserId){
		String mobile = RequestHolder.getParam();
		IecgUser my = userService.getOne(Wrappers.<IecgUser>query().lambda().eq(IecgUser::getName, mobile));
		if(my == null){
			return R.failed();
		}
		Long removeCount = redisTemplate.opsForSet().remove(CacheConstants.BIND_OTHERS + "_" + bindToUserId, my.getId());
		return R.ok(removeCount > 0);
	}


	/**
	 * 微信绑定设备
	 * @param iecgBindDto
	 * @return
	 */
	@ApiOperation(value = "设备绑定", notes = "设备绑定")
	@SysLog("设备绑定")
	@PostMapping(value = {"/device"})
	public R bindDevice(@RequestBody IecgBindDto iecgBindDto){
		String sn = iecgBindDto.getSn();
		String mobile = RequestHolder.getParam();
		String openId = iecgBindDto.getOpenId();
		IecgUser my = userService.getOne(Wrappers.<IecgUser>query().lambda().eq(IecgUser::getName, mobile).eq(IecgUser::getOpenId, openId));
		if(my == null){
			return R.failed("用户信息错误");
		}
		if(redisTemplate.opsForSet().isMember(CacheConstants.Device + "_" + my.getId(), sn)){
			return R.failed("设备已绑定");
		}

		redisTemplate.opsForSet().add(CacheConstants.Device + "_" + my.getId(), sn);
		return R.ok();

	}

	/**
	 * 微信绑定设备列表
	 * @param openId
	 * @return
	 */
	@ApiOperation(value = "设备绑定列表", notes = "设备绑定列表")
	@SysLog("设备绑定列表")
	@GetMapping("/binddevicelist/{openid}")
	public R bindDeviceList(@PathVariable("openid") String openId){
		IecgUser iecgUser = userService.getOne(Wrappers.<IecgUser>query().lambda().eq(IecgUser::getOpenId, openId));
		Set deviceSet = redisTemplate.opsForSet().members(CacheConstants.Device + "_" + iecgUser.getId());
		return R.ok(deviceSet);
	}


	/**
	 * 微信解除绑定设备
	 * @param sn 设备sn号
	 * @return
	 */
	@ApiOperation(value = "解除设备绑定", notes = "解除设备绑定")
	@SysLog("解除设备绑定")
	@DeleteMapping("/device/{sn}")
	public R delDevice(@PathVariable("sn") String sn){
		String mobile = RequestHolder.getParam();
		IecgUser my = userService.getOne(Wrappers.<IecgUser>query().lambda().eq(IecgUser::getName, mobile));
		if(my == null){
			return R.failed();
		}

		Long removeCount = redisTemplate.opsForSet().remove(CacheConstants.Device + "_" + my.getId(), sn);
		return R.ok(removeCount > 0);
	}


}
